<?php

namespace app\admin\controller;

use app\admin\BaseController;
use app\admin\model\Company;
use app\admin\model\Topic;
use app\admin\model\TopicOption;
use app\Request;
use think\db\Query;
use think\facade\Db;
use think\facade\Validate;


/* 
 * 题目管理
 */
class TopicController extends BaseController
{

    /**
     * 添加题目
     */
    public function addTopic(Request $request){
        $param = $request->param();
        $status = true;
        Db::startTrans();
        foreach ($param['info'] as $vv){
            $validate = Validate::rule([
                'title|题目' => 'require|max:500',
                'sort|序号' => 'require|number',
                'target|关联指标' => 'require|number',
            ]);

            if (!$validate->check($vv)){
                return $this->err_json($validate->getError());
            }

            if (empty($vv['option'])){
                return $this->err_json('请添加选项');
            }else{
                foreach ($vv['option'] as $v){
                    $validate = Validate::rule([
                        'sort|选项ABCD' => 'require|in:A,B,C,D',
                        'content|选项内容' => 'require|max:500',
                        'score|选项得分' => 'require|number',
                    ]);

                    if (!$validate->check($v)){
                        return $this->err_json($validate->getError());
                    }
                }
            }

            $topic = Topic::where('title',$vv['title'])->find();
            if (!empty($topic)){
                return $this->err_json('该题目已添加');
            }

            $topic = new Topic();
            $topic->title = $vv['title'];
            $topic->sort = $vv['sort'];
            $topic->target = $vv['target'];
            $info = $topic->save();
            $options = [];
            $v = [];
            foreach ($vv['option'] as $v){
                $data1 = [];
                $data1['topic_id'] = $topic->id;
                $data1['sort'] = $v['sort'];
                $data1['content'] = $v['content'];
                $data1['score'] = $v['score'];
                array_push($options,$data1);
            }

            $option = TopicOption::insertAll($options);
            if (!$info || !$option){
                $status = false;
            }

        }

        if ($status){
            Db::commit();
            return $this->suc_json('添加成功');
        }else{
            Db::rollback();
            return $this->err_json('添加失败');
        }

    }

    /**
     * 编辑题目
     */
    public function editTopic(Request $request){
        $param = $request->param();
        $validate = Validate::rule([
            'id|题目id' => 'require|number',
            'title|题目' => 'require|max:500',
            'sort|序号' => 'require|number',
            'target|关联指标' => 'require|number',
        ]);

        if (!$validate->check($param)){
            return $this->err_json($validate->getError());
        }

        if (empty($param['option'])){
            return $this->err_json('请添加选项');
        }else{
            foreach ($param['option'] as $v){
                $validate = Validate::rule([
                    'sort|选项ABCD' => 'require|in:A,B,C,D',
                    'content|选项内容' => 'require|max:500',
                    'score|选项得分' => 'require|number',
                ]);

                if (!$validate->check($v)){
                    return $this->err_json($validate->getError());
                }
            }
        }

        $topic = Topic::where('title',$param['title'])->where('id','<>',$param['id'])->find();
        if (!empty($topic)){
            return $this->err_json('该题目已添加');
        }
        Db::startTrans();
        $topic = Topic::where('id',$param['id'])->find();;
        $topic->title = $param['title'];
        $topic->sort = $param['sort'];
        $topic->target = $param['target'];
        $topic->update_time = date('Y-m-d H:i:s',time());
        $info = $topic->save();
        $options = [];
        foreach ($param['option'] as $v){
            $data1 = [];
            $data1['topic_id'] = $param['id'];
            $data1['sort'] = $v['sort'];
            $data1['content'] = $v['content'];
            $data1['score'] = $v['score'];
            array_push($options,$data1);
        }
        TopicOption::where('topic_id',$param['id'])->update([
            'is_del' => 1,
            'update_time' => date('Y-m-d H:i:s',time())
        ]);
        $option = TopicOption::insertAll($options);

        if ($info && $option){
            Db::commit();
            return $this->suc_json('编辑成功');
        }else{
            Db::rollback();
            return $this->err_json('编辑失败');
        }

    }


    /**
     * 删除题目
     */
    public function delTopic(Request $request){
        $param = $request->param();
        $validate = Validate::rule([
            'id|题目id' => 'require|number',
        ]);

        if (!$validate->check($param)){
            return $this->err_json($validate->getError());
        }

        $topic = Topic::where('id',$param['id'])->find();
        $topic->is_del = 1;
        $topic->update_time = date('Y-m-d H:i:s',time());
        $info = $topic->save();

        TopicOption::where('topic_id',$param['id'])->update([
            'is_del' => 1,
            'update_time' => date('Y-m-d H:i:s',time())
        ]);

        if ($info == 1){
            return $this->suc_json('删除成功');
        }else{
            return $this->err_json('删除失败');
        }


    }

    /**
     * 题目详情
     */
    public function topicDetail(Request $request){
        $param = $request->param();
        $validate = Validate::rule([
            'id|题目id' => 'require|number',
        ]);

        if (!$validate->check($param)){
            return $this->err_json($validate->getError());
        }

        $info = Topic::where('t.id',$param['id'])
            ->with([
                'option' => function(Query $query){
                    $query->where('is_del',2);
                    $query->order('sort asc');
                }
            ])
            ->alias('t')
            ->field(['t.*','tb.name target_name'])
            ->leftJoin('target_base tb','t.target = tb.id')
            ->find();


        if (!empty($info)){
            return $this->suc_json('',$info);
        }else{
            return $this->err_json('查询失败');
        }


    }

    /**
     * 题目列表
     */
    public function topicList(Request $request){
        $param = $request->param();
        $validate = Validate::rule([
            'perPage|分页' => 'require|number',
        ]);

        if (!$validate->check($param)){
            return $this->err_json($validate->getError());
        }

        $info = Topic::where('t.is_del',2)
            ->with([
                'option' => function(Query $query){
                    $query->where('is_del',2);
                    $query->order('sort asc');
                }
            ])
            ->where(function (Query $query) use ($param) {
                if (!empty($param['title']) && isset($param['title'])){
                    $query->where('t.title','like','%' . $param['title'] . '%');
                }
                if (!empty($param['target']) && isset($param['target'])){
                    $query->where('t.target',$param['target']);
                }
            })
            ->alias('t')
            ->field(['t.*','tb.name target_name','tb.letter target_letter'])
            ->leftJoin('target_base tb','t.target = tb.id')
            ->order('t.sort asc')
            ->paginate($param['perPage']);


        return $this->suc_json('',$info);


    }
    

}